# serial_thread.py
from PyQt5.QtCore import QObject, pyqtSignal, QThread
import serial
import time


class SerialWorker(QObject):
    data_received = pyqtSignal(bytes)  # 接收到数据的信号
    error_occurred = pyqtSignal(str)   # 错误信号

    def __init__(self, port, baud_rate, timeout=1):
        super().__init__()
        self.port = port
        self.baud_rate = baud_rate
        self.timeout = timeout
        self.running = False
        self.serial_conn = None

    def run(self):
        try:
            self.serial_conn = serial.Serial(self.port, self.baud_rate, timeout=self.timeout)
            self.running = True
            while self.running:
                if self.serial_conn.in_waiting > 0:
                    data = self.serial_conn.read(self.serial_conn.in_waiting)
                    self.data_received.emit(data)
                time.sleep(0.01)  # 避免 CPU 占用过高
        except Exception as e:
            self.error_occurred.emit(str(e))
        finally:
            if self.serial_conn and self.serial_conn.is_open:
                self.serial_conn.close()

    def stop(self):
        self.running = False
